package com.coding.easier.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author: D丶Cheng
 * @Description TODO
 * @Date 2021/11/15 17:11
 **/
public class HttpUtils {

    public static String post(String requestUrl, String data) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.setHeader(HttpHeaders.USER_AGENT,
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setEntity(new StringEntity(data));
            System.out.println("Executing request " + httpPost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            }
            else if (status == 429) {
                // Server returned HTTP response code: 429 for URL: https://translate.googleapis.com/translate_a/single?sl=ar&tl=en&client=gtx&dt=t&dt=bd&dt=rm&dt=qca&dj=1&ie=UTF-8&oe=UTF-8&hl=zh-CN&tk=607306.1013556
                throw new ClientProtocolException("请求次数过多，可能触发了限流，请稍候再试......");
            }
            else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }
    }
}
